package 设计模式;

import java.util.Scanner;

/**
 * @author shy_black
 * @date 2019/3/9 19:27
 * @Description: 模板模式的示例操作
 */
public class 模板模式 {

    public static void main(String[] args) {
//        Make coffee = new Coffee();
//        Make tea = new Tea();
        CaffeineBeverage coffee = new Coffee();
        coffee.prepareRecipe();
        CaffeineBeverage tea = new Tea();
        tea.prepareRecipe();

    }
}

abstract class CaffeineBeverage {
    //核心步骤
    //被声明为final以免子类改变这个算法的顺序
    final void prepareRecipe() {
        boilWater();
        brew();
        pourIncup();
        if (hook()) {
            addCondiments();
        }
    }

    final void boilWater() {
        System.out.println("把水烧开。。。");
    }

    final void pourIncup() {
        System.out.println("把饮料倒入杯中。。。");
    }

    //具体操作延迟到子类中实现
    abstract void brew();

    abstract void addCondiments();

    /**
     * 钩子方法，一类默认不做事的方法，
     * 子类可以视情况决定是否覆盖它
     */
    boolean hook() {
        return true;
    }
}

class Coffee extends CaffeineBeverage {

    @Override
    void brew() {
        System.out.println("冲泡咖啡。。。");
    }

    @Override
    void addCondiments() {
        System.out.println("加糖和咖啡。。。");

    }
    boolean hook() {
        System.out.println("请问您需要加糖和牛奶吗？？？ y/n");
        String result = getUserInfo();
        if(result.equals("y")) {
            return true;
        }else
            return false;
    }
    private String getUserInfo() {
        String str = null;
        Scanner sc = new Scanner(System.in);
        str = sc.nextLine();
        return str;
    }
}

class Tea extends CaffeineBeverage {

    @Override
    void brew() {
        System.out.println("冲泡茶叶。。。");
    }

    @Override
    void addCondiments() {
        System.out.println("加柠檬。。。");
    }
    boolean hook() {
        System.out.println("请问您需要加柠檬吗？？？ y/n");
        String result = getUserInfo();
        if(result.equals("y")) {
            return true;
        }else
            return false;
    }

    private String getUserInfo() {
        String str = null;
        Scanner sc = new Scanner(System.in);
        str = sc.nextLine();
        return str;
    }
}
